
package com.sm.shoplook.interceptor;

import com.sm.shoplook.dao.mapper.base.SensitivityMapper;
import com.sm.shoplook.domain.base.Sensitivity;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chenpy
 * @desc SensitivityFilter敏感词过滤
 * @date 2018/8/31 11:20
 * @see
 */
public class SensitivityFilter implements Filter {

	private static final Logger LOGGER = LoggerFactory.getLogger(SensitivityFilter.class);
	private static SensitivityMapper sensitivityMapper;
	static final Map<String, String> SENSITIVITIES_MAP = new HashMap<>();

	@Override
	public void init(FilterConfig filterConfig) {
	}

	public void init(ServletRequest request) {
	    if (SensitivityFilter.sensitivityMapper == null) {
            SensitivityFilter.sensitivityMapper = WebApplicationContextUtils.getRequiredWebApplicationContext(
                    request.getServletContext()).getBean(SensitivityMapper.class);
            // 加载敏感词
            List<Sensitivity> sensitivities = sensitivityMapper.selectAll();
            if (CollectionUtils.isNotEmpty(sensitivities)) {
                List<String> collect = sensitivities.stream().map(Sensitivity::getSensitivityValue)
                        .collect(Collectors.toList());
                for (String s : collect) {
                    SENSITIVITIES_MAP.put(s, s);
                }
            }
        }
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
	    init(request);
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		Map<String, String[]> parameterMap = request.getParameterMap();
		if (MapUtils.isEmpty(parameterMap) || httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
			chain.doFilter(request, response);
			return;
		}
		chain.doFilter(new RequestWrapper(httpServletRequest), response);
	}

	@Override
	public void destroy() {
	}
}
